<!--
 * @Descripttion:动态表头
 * @version: 
 * @Author: mmzhang
 * @Date: 2021-08-23 14:49:02
 * @LastEditTime: 2021-11-19 10:09:17
-->
<template>
  <div>
    <Modal v-model="dynamicFlag" :title="infoText?infoText.text1:'调整表头显示字段及排序'"
      @on-cancel="editDisplayFieldCancel('0')" width="850" :footer-hide="true"
      :mask-closable="false" class="subscribeModalStyle">
      <Row class="label_warp" v-if="tipsFlag">
        <Col span="24" class="tips">
        <Icon type="md-alert" class="tips_icon" />
        <div v-html="infoText.topTips"></div>
        </Col>
      </Row>
      <div class="transferBox">
        <div class="sourcedataBox">
          <div class="sourcedataBoxTit">
            <input :disabled="sourceList.length == 0" type="checkbox" id="sourceListLabel"
              @click="toggleAll(0)" :checked="selectedAllStatus(0)" />
            <label
              for="sourceListLabel">{{infoText?infoText.text2:"未在表头中显示"}}({{ sourceList.length }})</label>
          </div>

          <div class="sourcedataCon">
            <ul>
              <li v-for="(item, index) in sourceList" :key="index">
                <input type="checkbox" :disabled="item.disabled" :id="item.fieldValue+index"
                  v-model="item.isSelected" />
                <label :for="item.fieldValue+index">{{ item.fieldValue }}</label>
              </li>
            </ul>
          </div>
        </div>

        <div class="btnBox">
          <div class="btnBoxCenter">
            <span @click="toTarget" :class="[
                sourceList.length != 0 && sourceRefNum != 0
                  ? 'active'
                  : 'disabled',
                'ty-transfer-btn-toright to-switch',
              ]">
              <Button type="primary" :disabled="
                  sourceList.length != 0 && sourceRefNum != 0 ? false : true
                ">
                <Icon type="ios-arrow-forward" />
              </Button>
            </span>
            <span @click="toSource" :class="[
                targetList.length != 0 && targetRefNum != 0
                  ? 'active'
                  : 'disabled',
                'ty-transfer-btn-toleft to-switch',
              ]">
              <Button type="primary" :disabled="
                  targetList.length != 0 && targetRefNum != 0 ? false : true
                ">
                <Icon type="ios-arrow-back" />
              </Button>
            </span>
          </div>
        </div>

        <div class="sourcedataBox">
          <div class="sourcedataBoxTit">
            <input :disabled="targetList.length == 0" type="checkbox" id="targetListLabel"
              @click="toggleAll(1)" :checked="selectedAllStatus(1)" />
            <label for="targetListLabel">{{infoText?infoText.text3:"已在表头中显示"}}
              ({{ targetList.length }})</label>
          </div>

          <div class="sourcedataCon">
            <ul>
              <li v-for="(item, index) in targetList" :key="index">
                <input type="checkbox" :disabled="item.disabled"
                  :class="item.disabled? 'notCursor': ''" :id="item.fieldValue+index"
                  v-model="item.isSelected" />
                <label :for="item.fieldValue+index"
                  :class="[item.disabled? 'notCursor': '',item.lock?'colorBlue':'']">{{ item.fieldValue }}</label>
                <div class="upDown" v-if="!item.disabled">
                  <em v-if="iconLock" @click="lockItems(item,index)" :class="[
                      targetList.length != 0 && targetRefNum != 0
                        ? 'active' : 'disabled',
                        item.lock ? '' : 'MR40',
                      'ty-transfer-btn-tobottom to-switch',
                    ]">
                    <Icon :type="item.lock?'md-lock':'md-unlock'" size="20"
                      :color="item.lock ? '#2d8cf0' : '#c5c8ce'" />
                  </em>
                  <span v-show="(iconLock&&item.lock)||!iconLock">
                    <em @click="upItems(index)" :class="[
                      targetList.length != 0 && targetRefNum != 0
                        ? 'active'
                        : 'disabled',
                      'ty-transfer-btn-totop to-switch',
                    ]">
                      <Icon type="md-arrow-round-up" :disabled="true" size="20"
                        :color="index == disabledNum ? '#c5c8ce' : '#2d8cf0'" />
                    </em>
                    <em @click="downItems(item,index)" :class="[
                      targetList.length != 0 && targetRefNum != 0
                        ? 'active'
                        : 'disabled',
                      'ty-transfer-btn-tobottom to-switch',
                    ]">
                      <Icon type="md-arrow-round-down" size="20"
                        :color="
                        index == targetList.length - 1||(iconLock&&!targetList[index + 1].lock) ? '#c5c8ce' : 'red'" />
                    </em>
                  </span>
                </div>
              </li>
            </ul>
          </div>
          <div class="explain">
            <span>
              {{infoText?infoText.bottomText?infoText.bottomText:"说明：您可点击箭头，调整字段在表头中显示的位置":""}}
            </span>
          </div>
        </div>
      </div>

      <div class="transferFooter">
        <Button @click="editDisplayFieldCancel('1')">取消</Button>
        <Button type="info" v-if="preview" @click="previewEr">预览</Button>
        <Button type="info" @click="editDisplayFieldSave" v-preventReClick>保存</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
  export default {
    props: ['sourcedata', 'targetdata', 'preview', 'infoText', 'dataAll', 'iconLock',
      'tipsFlag'
    ],
    data() {
      return {
        dynamicFlag: false,
        sourceList: [],
        targetList: [],
        toTargetFlag: true,
        toSourceFlag: true,
        updateInfo: [],
      }
    },
    computed: {
      // 不可编辑项
      disabledNum() {
        return this.targetList.filter((item) => item.disabled).length
      },
      // 源数据中选中的数量
      sourceRefNum() {
        return this.sourceList.filter((item) => item.isSelected).length
      },
      // 目标数据中选中的数量
      targetRefNum() {
        return this.targetList.filter((item) => item.isSelected).length
      },
      // 选择的源记录数量
      selectSourceItemNumber() {
        return this.sourceList.filter((item) => item.isSelected).length
      },
      // 选择目标记录数量
      selectTargetItemNumber() {
        return this.targetList.filter((item) => item.isSelected).length
      },
    },
    directives: {
      preventReClick: {
        inserted(el, binding) {
          el.addEventListener('click', () => {
            if (!el.disabled) {
              el.disabled = true
              setTimeout(() => {
                el.disabled = false
              }, binding.value || 3000)
            }
          })
        }
      },
    },
    methods: {
      previewEr() {
        this.$emit('previewEr', this.targetList)
      },
      // 
      show() {
        this.dynamicFlag = true
      },
      hide() {
        this.dynamicFlag = false
      },
      // 编辑表头显示不显示
      editDisplayFieldSave() {
        this.updateInfo = []
        this.targetList.forEach((item, index) => {
          this.updateInfo.push({
            dbKey: item.dbKey,
            serialNo: index,
          })
        })
        this.reCustomerHeadUpdate()
      },
      // 保存修改的表头
      reCustomerHeadUpdate() {
        let params = {
          buildingId: Number(JSON.parse(this.$tool.getStorage('caseBuildingId'))),
          updateInfo: this.updateInfo,
        }
        if (this.dataAll) {
          let obj = {
            sourceList: this.sourceList,
            targetList: this.targetList
          }
          this.$emit('headUpdate', obj)
        } else if (this.preview) {
          this.$emit('headUpdate', this.targetList)
        } else {
          this.$emit('headUpdate', params)
        }

      },

      formatData(dataList) {
        let data = dataList.map((item) => {
          return {
            ...item,
            isSelected: false,
          }
        })
        return data
      },
      // 上移
      upItems(index) {
        if (index > this.disabledNum) {
          let update = this.targetList[index - 1]
          this.targetList.splice(index - 1, 1)
          this.targetList.splice(index, 0, update)
        } else {
          this.$Message.warning('已不可上移!')
        }
      },

      // 下移
      downItems(item, index) {
        if (this.iconLock) {
          if (index + 1 != this.targetList.length && this.targetList[index + 1].lock) {
            let downdate = this.targetList[index + 1]
            this.targetList.splice(index + 1, 1)
            this.targetList.splice(index, 0, downdate)
          } else {
            this.$Message.warning('已经是最后一条，不可下移!')
          }
        } else {
          if (index + 1 != this.targetList.length) {
            let downdate = this.targetList[index + 1]
            this.targetList.splice(index + 1, 1)
            this.targetList.splice(index, 0, downdate)
          } else {
            this.$Message.warning('已经是最后一条，不可下移!')
          }
        }
      },

      exchange(fd, td) {
        let selectedItem = fd.filter((item) => item.isSelected).map((item) => {
          return {
            ...item,
            isSelected: false,
          }
        })
        td.push(...selectedItem)
        var selectedlist = fd.filter((item) => !item.isSelected)
        return selectedlist
      },
      // 全选状态
      selectedAllStatus(type) {
        let disabledLen = this.targetList.filter((item) => item.disabled).length // 禁用项
        if (type == 0) {
          if (
            this.selectSourceItemNumber === this.sourceList.length &&
            this.selectSourceItemNumber !== 0
          ) {
            return true
          } else {
            return false
          }
        } else {
          if (
            this.selectTargetItemNumber + disabledLen !=
            this.targetList.length
          ) {
            return false
          } else {
            return true
          }
        }
      },
      // 全选及反选
      toggleAll(type) {
        if (type == 0) {
          let len = this.sourceList.length
          let slen = this.sourceList.filter((item) => item.isSelected).length
          if (len != slen) {
            this.sourceList.map((item) => (item.isSelected = item.disabled ? false : true))
          } else {
            this.sourceList.map((item) => (item.isSelected = false))
          }
        } else {
          let len = this.targetList.length // 未选中
          let slen = this.targetList.filter((item) => item.isSelected).length //已选中
          let disabledLen = this.targetList.filter((item) => item.disabled).length // 禁用项
          if (len != slen + disabledLen) {
            this.targetList.map((item) => {
              if (!item.disabled) {
                item.isSelected = true
              }
            })
          } else {
            this.targetList.map((item) => (item.isSelected = false))
          }
        }
      },
      // 把选择数据转移到目标（右框）
      toTarget() {
        this.sourceList = this.exchange(this.sourceList, this.targetList)
        //从左移到右 排序
        if (this.iconLock) {
          this.targetList = this.sortData(this.targetList, 'sort')
        }
      },
      // 把选择数据转回到源（左框）
      toSource() {
        if (this.iconLock) {
          let num = this.targetList.filter((item) => item.isSelected).length
          this.$Modal.confirm({
            title: '渠道移除确认',
            content: `请确认，是否将${num}个渠道从案场日报中移除？`,
            okText: '确认移除',
            closable: true,
            onOk: () => {
              this.onsuccess({
                type: 2,
              })
            }
          })
        } else {
          this.targetList = this.exchange(this.targetList, this.sourceList)
        }
      },

      //自定义table头部菜单配置 关闭
      editDisplayFieldCancel(val) {
        this.targetList = this.formatData(this.targetdata)
        this.sourceList = this.formatData(this.sourcedata)
        this.$emit('fieldCancel')
      },
      // 解锁/锁定
      lockItems(item, index) {
        if (item.lock) {
          this.$Modal.confirm({
            title: '渠道解锁确认',
            content: `请确认，是否解除渠道“${item.fieldValue}”的锁定？解除后，该渠道将无法在日报首页中优先显示`,
            okText: '确认解除',
            closable: true,
            onOk: () => {
              this.onsuccess({
                type: 1,
                item,
                index
              })
            }
          })
          return false
        }
        let lockNum = 1
        this.targetList.forEach(item => {
          if (item.lock) lockNum++
        })
        if (lockNum > 5 || item.lock) {
          this.$Message.warning('您至多可选择5个渠道锁定至日报首页')
        } else {
          item.lock = !item.lock
          this.targetList.splice(index, 1)
          this.targetList.unshift(item)
        }
      },
      onsuccess(val) {
        if (val.type == 1) {
          val.item.lock = !val.item.lock
          this.targetList = this.sortData(this.targetList, 'createTimes')
        } else if (val.type == 2) {
          this.targetList.forEach(item => {
            if (item.isSelected) item.lock = false
          })
          this.targetList = this.exchange(this.targetList, this.sourceList)
        }
      },
      // 取消锁定 添加显示 重新排序
      sortData(data, key) {
        let lockArr = [],
          arr = []
        data.forEach(item => {
          if (item.lock) {
            lockArr.push(item)
          } else {
            arr.push(item)
          }
        })
        arr.sort((a, b) => a[key] - b[key]);
        return lockArr.concat(arr)
      }
    },
    watch: {
      sourcedata(val) {
        this.sourceList = this.formatData(val)
      },
      targetdata(val) {
        this.targetList = this.formatData(val)
      },
    },
  }
</script>
<style lang="scss" scoped>
  .transferBox {
    width: 100%;
    max-height: 500px;
    display: flex;
    flex-direction: row;
    justify-content: space-between;

    .sourcedataBox {
      flex: 3;

      .sourcedataBoxTit {
        background: #f9fafc;
        margin: 0;
        line-height: normal;
        padding: 7px 16px;
        clear: both;
        color: #515a6e;
        font-size: 14px !important;
        white-space: nowrap;
        list-style: none;
        border: 1px solid #e8eaec;
        border-bottom: 0px;
        cursor: pointer;

        label {
          margin: 0 4px;
          vertical-align: 2px;
          font-size: 15px;
        }
      }

      .sourcedataCon {
        max-height: 400px;
        // min-height: 250px;
        height: 400px;
        overflow-y: auto;
        border: 1px solid #e8eaec;
        border-top: 0px;

        ul>li {
          margin: 0;
          line-height: normal;
          padding: 7px 16px;
          clear: both;
          color: #515a6e;
          font-size: 14px !important;
          white-space: nowrap;
          list-style: none;
          display: flex;
          flex-direction: row;
          position: relative;

          input {
            margin-top: 1px;
            cursor: pointer;
          }

          label {
            margin: 0 4px;
            cursor: pointer;
            min-width: 120px;
          }

          .upDown {
            position: absolute;
            right: 5px;
            cursor: pointer;
          }
        }
      }
    }

    .btnBox {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      max-height: 500px;

      .btnBoxCenter {
        display: flex;
        flex-direction: column;
        align-items: center;

        span {
          margin: 10px;
        }
      }
    }
  }

  .transferFooter {
    margin-top: 20px;
    text-align: center;

    button {
      width: 80px;
      margin: 0 10px;
    }
  }

  .notCursor {
    color: #c5c8ce;
    cursor: not-allowed !important;
  }

  .notClick {
    pointer-events: none;
  }

  .explain {
    overflow: hidden;
    margin-top: 8px;
    font-size: 12px;
    color: #999;
    line-height: 1.4;
  }

  .MR40 {
    margin-right: 40px;
  }

  .colorBlue {
    color: #2d8cf0;
  }

  .label_warp {
    margin-bottom: 15px;
    background-color: rgba(254, 252, 236, 1);
    width: auto;
    line-height: 32px;
    padding: 10px;

    .tips {
      line-height: 20px;
      font-size: 14px;
      display: flex;

      .tips_icon {
        font-size: 20px;
        color: #0f42a7;
        vertical-align: sub;
      }
    }
  }
</style>